package com.zj.weather.bgviews;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;


import java.util.ArrayList;
import java.util.List;

import com.zj.weather.R;
import com.zj.weather.base.BaseHolder;
import com.zj.weather.base.BaseWeatherBgView;
import com.zj.weather.base.HoldersInfo;
import com.zj.weather.utils.StaticValue;

import static com.zj.weather.utils.RandomUtils.getRandom;

/**
 * Created by zhaojie on 2017/9/14.
 */
public class FogDrawer extends BaseWeatherBgView {

    private static final int maxCount = 3;

    public FogDrawer(Context context) {
        super(context);
    }

    @Override
    protected List<HoldersInfo> getHolders() {
        List<HoldersInfo> infos = new ArrayList<>();
        infos.add(new HoldersInfo(maxCount) {
            @Override
            public FogHolder getHolderType(int position) {
                float scale = getRandom(1.13f, 1.77f);
                float offset = getRandom(0.66f, 0.85f);
                float cw = width * offset;
                float ch = cw / scale;
                return new FogHolder(ch, cw, width, height, position);
            }
        });
        return infos;
    }

    public static class FogHolder extends BaseHolder {
        private Drawable fog;
        private float alpha, w, h, curOffset;
        private int x, y;
        private float minX = 0.013f, maxX = 0.025f;
        private float speed = getRandom(minX, maxX);

        public FogHolder(float w, float h, int x, int y, int position) {
            super(x, y, position);
            this.w = w;
            this.h = h;
            this.x = x;
            this.y = (int) (y * getRandom(0.1f, 0.53f));
            this.curOffset = getRandom(-0.32f, 1.25f);
            float[] al = getCurAlpha();
            this.alpha = getRandom(al[0], al[1]) * 255f;
        }

        @Override
        public void initData(Context context) {
            fog = context.getResources().getDrawable(R.mipmap.fog);
        }

        @Override
        public void updateFrame(Context context, Canvas canvas, float changedAlpha) {
            curOffset += speed * getRandom(0.16f, 0.22f);
            float curX = curOffset * x - (w / 2f);
            if (curX > (x + w / 2f)) curOffset = 0.0f;
            int left = (int) (curX - w / 2f);
            int right = (int) (left + w);
            int top = (int) (y - h / 2f);
            int bottom = (int) (y + h / 2f);
            fog.setBounds(left, top, right, bottom);
            fog.setAlpha((int) (alpha * changedAlpha));
            fog.draw(canvas);
        }
    }

    private static float[] getCurAlpha() {
        float[] alpha = new float[2];
        if (StaticValue.isDay()) {
            alpha[0] = 0.65f;
            alpha[1] = 0.78f;
        } else {
            alpha[0] = 0.45f;
            alpha[1] = 0.52f;
        }
        return alpha;
    }
}

